package com.itany.book.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.exception.ManagerServiceException;
import com.itany.mapper.PermissionMapper;
import com.itany.pojo.Permission;
import com.itany.pojo.PermissionExample;
import com.itany.service.PermissionService;
import com.itany.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    PermissionMapper permissionMapper;

    @Transactional(readOnly = true)
    @Override
    public List<Permission> findAllModules() {
        PermissionExample example = new PermissionExample();
        example.or().andParentidEqualTo(0);
        List<Permission> list = permissionMapper.selectByExample(example);
        return list;
    }

    @Override
    public List<Permission> findAllModulesWithPermissionsByLoginUserId(Integer id) {

        List<Permission> list = permissionMapper.findAllModulesWithPermissionsByLoginUserId(id);
        return list;
    }

    @Override
    public List<Permission> findAllModulesWithPermission() {

        List<Permission> modules = permissionMapper.findModulesWithPermission();
        return modules;
    }

    @Override
    public void update(Permission p) throws ManagerServiceException {
        if (p.getId() == null) {
            throw new ManagerServiceException("缺少id");
        }
        permissionMapper.updateByPrimaryKeySelective(p);
    }

    @Override
    public PageInfo<Permission> findAllPermission(Integer page, Integer rows, String moduleName, String permissionName) {
        if (StringUtils.isEmpty(moduleName)) {
            moduleName = null;
        }
        if (StringUtils.isEmpty(permissionName)) {
            permissionName = null;
        }
        PageHelper.startPage(page, rows);
        List<Permission> list = permissionMapper.findAllPermission(moduleName, permissionName);
        PageInfo<Permission> info = new PageInfo<>(list);
        return info;
    }
}
